<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class OrderItem extends Model
{
    protected $fillable = [
        'order_id',
        'product_id',
        'product_name',
        'quantity',
        'price',
        'variant',
        'variant_name',
        'image'
    ];

    protected $appends = [
        'subtotal'
    ];

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * 获取商品规格
     */
    public function variant()
    {
        return $this->belongsTo(ProductVariant::class, 'variant');
    }

    /**
     * 计算小计
     */
    public function getSubtotalAttribute()
    {
        return $this->price * $this->quantity;
    }

    /**
     * 获取商品图片
     */
    public function getImageUrlAttribute()
    {
        if ($this->image) {
            return asset('storage/'.$this->image);
        }
        
        if ($this->product) {
            return $this->product->cover_image_url;
        }

        return asset('images/default-product.png');
    }
}